<?php


namespace app\admin\controller;


use app\admin\validate\UserValidate;
use app\BaseController;
use app\service\model\AdminModel;
use app\service\Token;
use app\service\Y;
use think\App;
use think\captcha\Captcha;
use think\Session;

class Login extends BaseController
{

    /**
     * 登录
     * @param UserValidate $user_validate
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function check_login(UserValidate $user_validate): \think\response\Json
    {
        $user_validate->goCheck('admin_login');
        $param = $user_validate->getDataByRule();

        $admin = AdminModel::where('username', '=', $param['username'])->find();

        if (!$admin) {
            return Y::error('用户不存在');
        }

        if (md5($param['password'] . $admin->salt) !== $admin->password) {
            return Y::error('密码错误', [$param['password'] . $admin->salt, md5($param['password'] . $admin->salt), $admin->password]);
        }

        $token = Token::getAdminToken($admin->id)['token'];

        return Y::success(['token' => $token], '登录成功');
    }
}